package tools

import (
	"fmt"

	"github.com/go-playground/locales/zh"
	ut "github.com/go-playground/universal-translator"
	"github.com/go-playground/validator/v10"
	chTranslations "github.com/go-playground/validator/v10/translations/zh"
)

var (
	validate *validator.Validate
	trans    ut.Translator
)

var MapValKey = struct {
	name string
}{
	name: "validation func",
}

func init() {
	validate = validator.New()

	if err := transInit(); err != nil {
		panic(err)
	}
}

func transInit() (err error) {
	uni := ut.New(zh.New(), zh.New())
	trans, _ = uni.GetTranslator("zh")
	return chTranslations.RegisterDefaultTranslations(validate, trans)
}

func ValidateStruct(obj interface{}) error {
	err := validate.Struct(obj)
	if err == nil {
		return nil
	}

	if validationErrors, ok := err.(validator.ValidationErrors); ok {
		return fmt.Errorf("%v", validationErrors.Translate(trans))
	} else {
		return err
	}
}
